package battlenetwork;

import java.awt.Point;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;



public class Game implements Observer {
	static final int DIRECTION_UP    = 0;
	static final int DIRECTION_LEFT  = 1;
	static final int DIRECTION_DOWN  = 2;
	static final int DIRECTION_RIGHT = 3;
	MainFrame mainFrame;
	Tile[][] tiles;
	MyKeyListener keyListener;
	Point playerPos;
	
	public Game(){
		keyListener = new MyKeyListener(this);
		this.mainFrame = new MainFrame(keyListener);
		mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		tiles = new Tile[6][3];
		for(int i = 0; i < 6; i++){
			for(int j = 0; j < 3; j++){
				tiles[i][j] = new Tile();
				tiles[i][j].addObserver(this);
				if(i < 3){
					tiles[i][j].setFriendly(true);
				}
			}
		}
		playerPos = new Point(1,1);
		tiles[5][1].setUnit(new Unit(3));
		tiles[4][2].setUnit(new Unit(3));
		tiles[5][2].setUnit(new Unit(3));
		redraw();
	}
	
	public boolean isFreeForPlayer(Point p){
		if((p.x < 0) || (p.x > 5) || (p.y < 0) || (p.y > 2)){
			return false;
		}
		if(!tiles[p.x][p.y].isFriendly()){
			return false;
		}
		return tiles[p.x][p.y].isFree();
	}
	
	public void movePlayRel(int direction){
		switch (direction){
		case DIRECTION_UP:
			if(isFreeForPlayer(new Point(playerPos.x, playerPos.y-1))){
				playerPos.y--;
				
				
			}
			break;
		case DIRECTION_LEFT:
			if(isFreeForPlayer(new Point(playerPos.x-1, playerPos.y))){
				playerPos.x--;
				
				
			}
			
			break;
		case DIRECTION_DOWN:
			if(isFreeForPlayer(new Point(playerPos.x, playerPos.y+1))){
				playerPos.y++;
				
			}
			
			break;
		case DIRECTION_RIGHT:
			if(isFreeForPlayer(new Point(playerPos.x+1, playerPos.y))){
				playerPos.x++;
				
				
			}
			
			break;
			
		}
		redraw();
	}
	
	public void fireMain(){
		for(int i = playerPos.x+1; i < 6; i++){
			if(!tiles[i][playerPos.y].isFree()){
				tiles[i][playerPos.y].damage(1);
				break;
			}
		}
	}
	
	
	
	public Point getPlayerPos(){
		return playerPos;
	}
	
	public Tile[][] getTiles(){
		return tiles;
	}
	
	public void redraw(){
		mainFrame.redraw(this);
	}

	@Override
	public void update(Observable o, Object arg) {
		redraw();
		
	}
	

}
